import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Upload, Avatar, Tabs, message, Skeleton, Row, Col, Statistic } from 'antd';
import { UserOutlined, MailOutlined, HomeOutlined, GlobalOutlined, UploadOutlined } from '@ant-design/icons';
import { getUserProfile, updateUserProfile, updateUserAvatar, getUserStats } from '../../api/user';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { RcFile } from 'antd/es/upload';

const { TabPane } = Tabs;

const ProfilePage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const [avatarLoading, setAvatarLoading] = useState(false);
  const [userProfile, setUserProfile] = useState<any>(null);
  const [stats, setStats] = useState({
    knowledgeCount: 0,
    categoryCount: 0,
    tagCount: 0,
    storageUsed: 0,
    storageLimit: 1024 * 1024 * 1024, // 默认1GB
  });

  useEffect(() => {
    fetchUserProfile();
    fetchUserStats();
  }, []);

  const fetchUserProfile = async () => {
    try {
      setLoading(true);
      const profile = await getUserProfile();
      setUserProfile(profile);
      form.setFieldsValue({
        nickname: profile.nickname,
        email: profile.email,
        bio: profile.bio,
        location: profile.location,
        website: profile.website,
      });
    } catch (error) {
      console.error('获取用户资料失败:', error);
      message.error('获取用户资料失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchUserStats = async () => {
    try {
      const statsData = await getUserStats();
      setStats(statsData);
    } catch (error) {
      console.error('获取用户统计信息失败:', error);
    }
  };

  const handleUpdateProfile = async (values: any) => {
    try {
      await updateUserProfile(values);
      message.success('个人资料更新成功');
      fetchUserProfile();
    } catch (error) {
      console.error('更新个人资料失败:', error);
      message.error('更新个人资料失败');
    }
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleAvatarChange: UploadProps['onChange'] = async (info) => {
    if (info.file.status === 'uploading') {
      setAvatarLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      try {
        const response = await updateUserAvatar(info.file.originFileObj as RcFile);
        setUserProfile({
          ...userProfile,
          avatar: response.avatar,
        });
        message.success('头像更新成功');
      } catch (error) {
        console.error('头像上传失败:', error);
        message.error('头像上传失败');
      } finally {
        setAvatarLoading(false);
      }
    }
  };

  // 格式化存储空间
  const formatStorage = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  };

  // 计算存储空间使用百分比
  const storagePercent = Math.round((stats.storageUsed / stats.storageLimit) * 100);

  if (loading) {
    return (
      <Card>
        <Skeleton active avatar paragraph={{ rows: 6 }} />
      </Card>
    );
  }

  return (
    <Card>
      <Tabs defaultActiveKey="profile">
        <TabPane tab="个人资料" key="profile">
          <Row gutter={[24, 24]}>
            <Col xs={24} md={8}>
              <div style={{ textAlign: 'center', marginBottom: 24 }}>
                <Avatar
                  size={120}
                  src={userProfile?.avatar}
                  icon={!userProfile?.avatar && <UserOutlined />}
                />
                <div style={{ marginTop: 16 }}>
                  <Upload
                    name="avatar"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    onChange={handleAvatarChange}
                  >
                    <Button 
                      icon={<UploadOutlined />} 
                      loading={avatarLoading}
                    >
                      更换头像
                    </Button>
                  </Upload>
                </div>
                <div style={{ marginTop: 24 }}>
                  <h3>{userProfile?.nickname}</h3>
                  <p>{userProfile?.username}</p>
                </div>
              </div>
            </Col>
            <Col xs={24} md={16}>
              <Form
                form={form}
                layout="vertical"
                onFinish={handleUpdateProfile}
                initialValues={{
                  nickname: userProfile?.nickname,
                  email: userProfile?.email,
                  bio: userProfile?.bio,
                  location: userProfile?.location,
                  website: userProfile?.website,
                }}
              >
                <Form.Item
                  name="nickname"
                  label="昵称"
                  rules={[{ required: true, message: '请输入昵称' }]}
                >
                  <Input prefix={<UserOutlined />} placeholder="昵称" />
                </Form.Item>
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入有效的邮箱地址' },
                  ]}
                >
                  <Input prefix={<MailOutlined />} placeholder="邮箱" disabled />
                </Form.Item>
                <Form.Item name="bio" label="个人简介">
                  <Input.TextArea rows={4} placeholder="介绍一下自己吧" />
                </Form.Item>
                <Form.Item name="location" label="所在地">
                  <Input prefix={<HomeOutlined />} placeholder="所在地" />
                </Form.Item>
                <Form.Item name="website" label="个人网站">
                  <Input prefix={<GlobalOutlined />} placeholder="个人网站" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    保存修改
                  </Button>
                </Form.Item>
              </Form>
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="账户统计" key="stats">
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic title="知识总数" value={stats.knowledgeCount} />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic title="分类总数" value={stats.categoryCount} />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic title="标签总数" value={stats.tagCount} />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic 
                  title="存储空间" 
                  value={formatStorage(stats.storageUsed)} 
                  suffix={`/ ${formatStorage(stats.storageLimit)} (${storagePercent}%)`} 
                />
              </Card>
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="安全设置" key="security">
          <p>密码修改功能开发中...</p>
        </TabPane>
      </Tabs>
    </Card>
  );
};

export default ProfilePage;